package com.qf.smsplatform.monitor.mq;


import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.RabbitMQConstants;

import com.qf.smsplatform.monitor.api.CacheService;
import com.qf.smsplatform.monitor.utils.JavaMailUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.io.IOException;
import java.util.Set;

/**
 * @Author: LeeRui
 * 2021/2/3 下午 7:29
 **/
@Component
@Slf4j
public class MonitorQueueMessageJob implements SimpleJob {

    @Autowired
    private ConnectionFactory connectionFactory;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private JavaMailUtil javaMailUtil;

    @Override
    public void execute(ShardingContext shardingContext) {

        //监听MQ中的队列
        //获取连接创建channel
        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(false);

        //查询全部通道信息
        Set<String> channelIds = cacheService.smembers(CacheConstants.CACHE_PREFIX_SMS_CHANNEL_ALL);
        //遍历channelIds
        for (String channelId : channelIds) {
            //声明队列名称
            String queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + channelId;
            // 创建队列
            try {
                channel.queueDeclare(queueName, true, false, false, null);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 获取队列中的消息数量
            int messageCount = 0;
            try {
                messageCount = channel.queueDeclarePassive(queueName).getMessageCount();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 判断消息数量
            if (messageCount > 2) {
                // 发送邮件通知消息堆积
                log.info("【监控模块】 {}队列中的消息,出现了消息堆积，消息的数量为：{}", queueName, messageCount);
                //发送邮件
                try {
                    javaMailUtil.sendMailForQueue(queueName, messageCount);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            } else {
                log.info("【监控模块】 {}队列中的消息，没有出现堆积问题！", queueName);
            }
        }
    }
}
